#!/usr/bin/python
# process_string.py : Sends a sentence to the TRIPS page and gets its semantics analysis and parse.
# using BeautifulSoup HMTL parser.
# Author: Federico Cirett Galan / Raquel Torres Peralta
PGK = "ua_cs665_trips"

from urllib2 import urlopen
#from ClientForm import ParseResponse
from BeautifulSoup import BeautifulSoup
import getopt
import re
import types
import time
import sys
import string
# ROS 
import roslib; roslib.load_manifest('ua_cs665_trips')
import rospy
#from std_msgs.msg import String
#from ua_cs665_trips.srv import *
from ua_cs665_trips.msg import *
#
       
def handle_process_string(req):
    sentence = req.sentence
    query = sentence.replace(' ','+')
    trips_url = "http://www.cs.rochester.edu/research/cisd/projects/trips/parser/cgi/web-parser-xml.cgi?input="
    url = trips_url+query
    print url
    page = urlopen(url)
    soup = BeautifulSoup(page)
    words = soup.findAll('words')
    t_words = words[1].findAll('lisp')
    text_words = t_words[0].text
    tree = soup.findAll('tree')
    t_tree = tree[1].findAll('lisp')
    text_tree = t_tree[0].text
    terms = soup.findAll('terms')
    t_term = terms[1].findAll('lisp')
    text_term= t_term[0].text
    if text_term != 'NIL':
      print "WORDS"
      print text_words
      print "TREE"
      print text_tree
      print "RDF"
      print text_term
      pub = rospy.Publisher('trips_output', TripsOutput)
      pub.publish(lisp_words=text_words, lisp_tree=text_tree, lisp_rdf=text_term)
    else:
      print "The sentence '%s' failed to parse\n" % sentence
    
def process_string_listener():
    rospy.init_node('process_sentence_listener')
    rospy.Subscriber('process_sentence', Sentence, handle_process_string)
    print "Ready to process strings."
    rospy.spin()

if __name__ == "__main__":
    process_string_listener()
